package com.ui.element;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

import com.ui.event.HexKeyCall;

public class HexComboBox extends JComboBox<Object> {

	private static final long serialVersionUID = 2057496183322086625L;

	public HexComboBox() {
		super();
		setFont(EleConsts.FONT_DEF);
		addOption("", "");
	}

	Map<String, String> options = new HashMap<String, String>();

	/**
	 * @Description 加入一个选择项
	 * @param @param id
	 * @param @param showValue 参数
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void addOption(String id, String showValue) {
		options.put(showValue, id);
		Object[] cs = options.keySet().toArray();
		setModel(new DefaultComboBoxModel(cs));
	}

	/**
	 * @Description 加入多个选择项
	 * @param @param ops [String id,String showValue]
	 * @return void 返回类型
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void addOption(String[]... ops) {
		for (String[] option : ops) {
			options.put(option[1], option[0]);
		}
		Object[] cs = options.keySet().toArray();
		setModel(new DefaultComboBoxModel(cs));
	}

	/* 默认显示值 */
	/**
	 * @Description 设置空值时的默认显示
	 * @param @param text 参数
	 * @return void 返回类型
	 * @throws
	 */
	public void setPlaceholder(String text) {
		addFocusListener(focuAdp);
		Rectangle bs = this.getBounds();
		mask.setText(text);
		mask.setForeground(Color.lightGray);
		mask.setBounds(2, 0, bs.width - 2, bs.height - 2);
		this.add(mask);
	}

	FocusListener focuAdp = new FocusListener() {
		public void focusGained(FocusEvent arg0) {
			mask.setVisible(false);
		}

		public void focusLost(FocusEvent arg0) {
			Object obj = getSelectedItem();
			if (obj == null || "".equals(obj.toString())) {
				mask.setVisible(true);
			}
		}
	};

	HexLabel mask = new HexLabel();
	/* 默认显示值 */

	/* 键盘监听 */
	private HexKeyCall call;

	KeyAdapter adap = new KeyAdapter() {
		public void keyPressed(KeyEvent e) {
			call.callBack(e);
		}
	};

	public void keyPressedCall(HexKeyCall call) {
		this.call = call;
		addKeyListener(adap);
	}

	/* 键盘监听 */
	
	/**
	 * @Description 当前选择项的显示值
	 * @param @return 参数
	 * @return String 返回类型 
	 * @throws
	 */
	public String getShowChar() {
		String str = null;
		Object obj = getSelectedItem();
		if (obj != null) {
			str = obj.toString();
		}
		return str;
	}
	
	/**
	 * @Description 当前选择项的隐藏值
	 * @param @return 参数
	 * @return String 返回类型 
	 * @throws
	 */
	public String getShowId() {
		String str = null;
		Object obj = getSelectedItem();
		if (obj != null) {
			str = options.get(obj.toString());
		}
		return str;
	}

}
